// app/page.tsx
'use client';

import { useState, useEffect } from 'react';
import VotingForm from '@/components/VotingForm';
import ResultsDisplay from '@/components/ResultsDisplay';
import { getResults, Option, ResultsResponse } from '@/lib/api';
import Link from "next/link";
export default function Home() {
  const [results, setResults] = useState<ResultsResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const fetchResults = async () => {
    try {
      setLoading(true);
      const data = await getResults();
      setResults(data);
      setError('');
    } catch (err) {
      setError('获取数据失败');
      console.error('Error fetching results:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchResults();
  }, []);

  const handleVoteSuccess = () => {
    // 投票成功后重新获取结果
    fetchResults();
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="text-lg">加载中...</div>
      </div>
    );
  }

  if (error || !results) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="text-red-600">{error || '获取数据失败'}</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-100 py-8">
      <div className="container mx-auto px-4">
        <div className="text-center mb-8">
          <h1 className="text-4xl font-bold text-gray-800 mb-2">投票系统</h1>
          <p className="text-gray-600">请选择您最喜欢的选项</p>
		  <Link 
		            href="/results" 
		            className="inline-block mt-4 text-blue-600 hover:text-blue-800 underline"
		          >
		            查看完整结果页面 →
		          </Link>
        </div>

        <div className="grid md:grid-cols-2 gap-8 max-w-4xl mx-auto">
          {/* 投票表单 */}
          <div>
            <VotingForm
              options={results.options}
              topic={results.topic}
              onVoteSuccess={handleVoteSuccess}
            />
          </div>

          {/* 实时结果 */}
          <div>
            <ResultsDisplay
              options={results.options}
              topic={results.topic}
            />
            
            <div className="mt-4 text-center">
              <button
                onClick={fetchResults}
                className="bg-gray-600 text-white py-2 px-4 rounded-lg hover:bg-gray-700"
              >
                刷新结果
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}